package com.buaa.divinationmaster.algorithm;

import java.util.ArrayList;
import java.util.List;

/**
 * 金钱卦算法
 * 实现六爻金钱卦的生成和解读逻辑
 */
public class CoinAlgorithm {
    
    /**
     * 爻象类型
     */
    public enum YaoType {
        YOUNG_YIN("少阴", "⚋⚋", false, 8),      // 二背一正
        YOUNG_YANG("少阳", "⚊", false, 7),      // 二正一背  
        OLD_YIN("老阴", "⚋⚋", true, 6),        // 三正（动爻）
        OLD_YANG("老阳", "⚊", true, 9);         // 三背（动爻）
        
        private final String name;
        private final String symbol;
        private final boolean isChanging;
        private final int number;
        
        YaoType(String name, String symbol, boolean isChanging, int number) {
            this.name = name;
            this.symbol = symbol;
            this.isChanging = isChanging;
            this.number = number;
        }
        
        public String getName() { return name; }
        public String getSymbol() { return symbol; }
        public boolean isChanging() { return isChanging; }
        public int getNumber() { return number; }
    }
    
    /**
     * 硬币投掷结果
     */
    public static class CoinThrow {
        private int coin1;  // 0=背面，1=正面
        private int coin2;
        private int coin3;
        private YaoType yaoType;
        
        public CoinThrow(int coin1, int coin2, int coin3) {
            this.coin1 = coin1;
            this.coin2 = coin2;
            this.coin3 = coin3;
            this.yaoType = calculateYaoType();
        }
        
        private YaoType calculateYaoType() {
            // 背面值3，正面值2
            int total = (coin1 == 0 ? 3 : 2) + (coin2 == 0 ? 3 : 2) + (coin3 == 0 ? 3 : 2);
            
            switch (total) {
                case 6: return YaoType.OLD_YIN;    // 三正
                case 7: return YaoType.YOUNG_YANG; // 二正一背
                case 8: return YaoType.YOUNG_YIN;  // 二背一正
                case 9: return YaoType.OLD_YANG;   // 三背
                default: return YaoType.YOUNG_YIN; // 默认
            }
        }
        
        public int getCoin1() { return coin1; }
        public int getCoin2() { return coin2; }
        public int getCoin3() { return coin3; }
        public YaoType getYaoType() { return yaoType; }
    }
    
    /**
     * 六爻卦象
     */
    public static class Hexagram {
        private List<YaoType> yaos;
        private String name;
        private String upperTrigram;
        private String lowerTrigram;
        
        public Hexagram(List<YaoType> yaos) {
            this.yaos = new ArrayList<>(yaos);
            calculateHexagram();
        }
        
        private void calculateHexagram() {
            // 简化的卦象计算
            StringBuilder upper = new StringBuilder();
            StringBuilder lower = new StringBuilder();
            
            // 下卦（初爻、二爻、三爻）
            for (int i = 0; i < 3; i++) {
                lower.append(yaos.get(i).getSymbol().contains("⚊") ? "1" : "0");
            }
            
            // 上卦（四爻、五爻、六爻）  
            for (int i = 3; i < 6; i++) {
                upper.append(yaos.get(i).getSymbol().contains("⚊") ? "1" : "0");
            }
            
            this.lowerTrigram = getTrigramName(lower.toString());
            this.upperTrigram = getTrigramName(upper.toString());
            this.name = upperTrigram + lowerTrigram + "卦";
        }
        
        private String getTrigramName(String pattern) {
            switch (pattern) {
                case "111": return "乾";  // 三阳爻
                case "110": return "兑";  // 上阳中阳下阴
                case "101": return "离";  // 上阳中阴下阳
                case "100": return "震";  // 上阳中阴下阴
                case "011": return "巽";  // 上阴中阳下阳
                case "010": return "坎";  // 上阴中阳下阴
                case "001": return "艮";  // 上阴中阴下阳
                case "000": return "坤";  // 三阴爻
                default: return "未知";
            }
        }
        
        public List<YaoType> getYaos() { return yaos; }
        public String getName() { return name; }
        public String getUpperTrigram() { return upperTrigram; }
        public String getLowerTrigram() { return lowerTrigram; }
    }
    
    /**
     * 金钱卦读象结果
     */
    public static class CoinReading {
        private String question;
        private List<CoinThrow> coinThrows;
        private Hexagram hexagram;
        private String interpretation;
        private long timestamp;
        
        public CoinReading(String question, List<CoinThrow> coinThrows) {
            this.question = question;
            this.coinThrows = new ArrayList<>(coinThrows);
            this.timestamp = System.currentTimeMillis();
            
            // 从投掷结果生成六爻
            List<YaoType> yaos = new ArrayList<>();
            for (CoinThrow coinThrow : coinThrows) {
                yaos.add(coinThrow.getYaoType());
            }
            
            this.hexagram = new Hexagram(yaos);
            this.interpretation = generateInterpretation();
        }
        
        private String generateInterpretation() {
            StringBuilder sb = new StringBuilder();
            
            sb.append("【").append(hexagram.getName()).append("解读】\n\n");
            
            // 卦象基本信息
            sb.append("卦象组成：\n");
            sb.append("上卦：").append(hexagram.getUpperTrigram()).append("\n");
            sb.append("下卦：").append(hexagram.getLowerTrigram()).append("\n\n");
            
            // 六爻详解
            sb.append("六爻详解：\n");
            String[] yaoNames = {"初爻", "二爻", "三爻", "四爻", "五爻", "六爻"};
            
            for (int i = 0; i < hexagram.getYaos().size(); i++) {
                YaoType yao = hexagram.getYaos().get(i);
                sb.append(yaoNames[i]).append("：").append(yao.getName())
                  .append(" ").append(yao.getSymbol());
                
                if (yao.isChanging()) {
                    sb.append("（动爻）");
                }
                sb.append("\n");
            }
            
            sb.append("\n【综合分析】\n");
            sb.append(getHexagramInterpretation(hexagram));
            
            // 动爻分析
            List<YaoType> changingYaos = new ArrayList<>();
            for (YaoType yao : hexagram.getYaos()) {
                if (yao.isChanging()) {
                    changingYaos.add(yao);
                }
            }
            
            if (!changingYaos.isEmpty()) {
                sb.append("\n\n【动爻分析】\n");
                sb.append("共有").append(changingYaos.size()).append("个动爻，");
                sb.append("表示此卦有变化之象，需要特别关注动爻所示的变化趋势。");
            }
            
            sb.append("\n\n【建议】\n");
            sb.append(getAdvice(hexagram));
            
            return sb.toString();
        }
        
        private String getHexagramInterpretation(Hexagram hexagram) {
            // 根据不同卦象返回相应解释
            String name = hexagram.getName();
            
            if (name.contains("乾")) {
                return "乾卦象征天，代表刚健、主动、创造力。此时宜积极进取，把握时机。";
            } else if (name.contains("坤")) {
                return "坤卦象征地，代表柔顺、包容、承载。此时宜以柔克刚，顺势而为。";
            } else if (name.contains("震")) {
                return "震卦象征雷，代表动荡、震动、新的开始。变化正在发生或即将来临。";
            } else if (name.contains("巽")) {
                return "巽卦象征风，代表渐进、温和、持续。事情会缓慢但稳定地发展。";
            } else if (name.contains("坎")) {
                return "坎卦象征水，代表险阻、流动、智慧。需要谨慎应对，以智慧化解困难。";
            } else if (name.contains("离")) {
                return "离卦象征火，代表光明、智慧、文明。前景光明，但需要保持理智。";
            } else if (name.contains("艮")) {
                return "艮卦象征山，代表静止、稳定、阻止。适合静观其变，不宜轻举妄动。";
            } else if (name.contains("兑")) {
                return "兑卦象征泽，代表喜悦、沟通、和悦。人际关系和谐，有利于合作。";
            } else {
                return "此卦象征变化与平衡，建议综合考虑各方面因素，审慎决策。";
            }
        }
        
        private String getAdvice(Hexagram hexagram) {
            String name = hexagram.getName();
            
            if (name.contains("乾")) {
                return "天行健，君子以自强不息。积极主动，把握机遇，但要注意适度。";
            } else if (name.contains("坤")) {
                return "地势坤，君子以厚德载物。保持谦逊包容的态度，以柔制刚。";
            } else {
                return "根据卦象指示，建议您保持耐心，顺应自然规律，做出明智的选择。";
            }
        }
        
        // Getters
        public String getQuestion() { return question; }
        public List<CoinThrow> getCoinThrows() { return coinThrows; }
        public Hexagram getHexagram() { return hexagram; }
        public String getInterpretation() { return interpretation; }
        public long getTimestamp() { return timestamp; }
    }
}
